import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ttlock_flutter/ttlock.dart";

enum UsageTimeType {
  usage, // 限时
  forever, // 永久
}

class TabPane extends StatefulWidget {
  final UsageTimeType usageTimeType;
  final Map lockInfo;
  const TabPane({super.key, required this.usageTimeType, required this.lockInfo});

  @override
  State<StatefulWidget> createState() => _TabPaneState();

}

class _TabPaneState extends State<TabPane> {

  bool forever = false;
  final DateTime currentDate = DateTime.now();
  final Map _params = {
    "cardName": "",
    "startDate": DateTime.now(),
    "endDate": DateTime.now(),
    "lockId": null,
    "cardNumber": "",
  };

  @override
  void initState() {
    super.initState();
    // 初始化默认时间
    setState(() {
      _params["lockId"] = widget.lockInfo["lockId"];
    });
    _initDefaultTimes();
  }


  // 初始化默认时间
  void _initDefaultTimes() {
    final now = DateTime.now();
    _params["startDate"] = now;
  }

  /// 添加IC卡
  void _addCard() async {
    if (!_validate()) return;
    EasyLoading.showToast("准备添加IC卡");
    TTLock.addCard(
        null,
        DateTime.parse(DateTools.formatYMD(_params["startDate"], format: "{y}-{m}-{d} {h}:{i}")).millisecond,
        DateTime.parse(DateTools.formatYMD(_params["endDate"], format: "{y}-{m}-{d} {h}:{i}")).millisecond,
        widget.lockInfo["lockData"],
        () {
          EasyLoading.showToast("请将IC卡放置到刷卡区");
        },
        (cardNumber) {
          print(cardNumber);
          setState(() {
            _params["cardNumber"] = cardNumber;
          });
          Map<String, dynamic> params = {
            ..._params,
            "startDate": DateTools.formatYMD(_params["endDate"], format: "{y}-{m}-{d} {h}:{i}:{s}"),
            "endDate": DateTools.formatYMD(_params["endDate"], format: "{y}-{m}-{d} {h}:{i}:{s}"),
          };
          lockApi.addCard(int.parse(widget.lockInfo["lockId"]), params);
          EasyLoading.showSuccess("添加成功");
          Stacker.pop(true);
        },
        (error, message) {
          print("$error:>>>$message");
          EasyLoading.showError("添加失败");
        }
    );
  }

  bool _validate() {
    if (_params["cardName"].isEmpty) {
      EasyLoading.showToast("姓名不能为空");
      return false;
    }
    if (_params["startDate"].isAfter(_params["endDate"])) {
      EasyLoading.showToast("失效时间不能小于生效时间");
      return false;
    }
    return true;
  }

  List<Widget> _usageTime() {
    if (widget.usageTimeType == UsageTimeType.usage) {
      return [
        const SizedBox(height: 12,),
        MenuBlock(
            items: [
              MenuBlockItem(
                text: "生效时间",
                suffix: Text(
                  DateTools.formatTime(_params["startDate"].millisecondsSinceEpoch, format: "{y}-{m}-{d} {h}:{i}"),
                  style: const TextStyle(color: ThemeVars.colorTextTer),
                ),
                onTap: () {
                  showDatetimePicker(
                    context: context,
                    initialDateTime: _params["startDate"],
                    onchange: (value) => setState(() {
                      if (value != null) _params["startDate"] = value;
                    }),
                  );
                },
              ),
              MenuBlockItem(
                text: "失效时间",
                showArrow: true,
                suffix: Text(
                  DateTools.formatTime(_params["endDate"].millisecondsSinceEpoch, format: "{y}-{m}-{d} {h}:{i}"),
                  style: const TextStyle(color: ThemeVars.colorTextTer),
                ),
                onTap: () {
                  showDatetimePicker(
                    context: context,
                    initialDateTime: _params["endDate"],
                    onchange: (value) => setState(() {
                      if (value != null)  {
                        if (value.isAfter(_params["startDate"])) {
                          _params["endDate"] = value;
                        } else {
                          EasyLoading.showToast("失效时间不能小于生效时间");
                        }

                      };
                    }),
                  );
                },
              ),
            ]
        ),
      ];
    } else {
      return [];
    }
  }

  List<Widget> _renderContent() {
    return [
      MenuBlock(
          items: [
            MenuBlockItem(
                text: "姓名",
                showArrow: false,
                suffix: TextField(
                  textAlign: TextAlign.right,
                  decoration: const InputDecoration(
                    hintText: "请给密码命名",
                    isDense: true,
                  ),
                  onChanged: (value) => setState(() {
                    _params["cardName"] = value;
                  }),
                )
            ),
          ]
      ),
      ..._usageTime(),
      SizedBox(height: 36,),
      Button(
        radius: 6,
        type: ButtonType.primary,
        onPressed: () {
          _addCard();
        },
        child: const Text("确定"),
      ),
    ];
  }


  @override
  Widget build(BuildContext context) {
    return ListView(
      padding: const EdgeInsets.all(ThemeVars.paddingPage),
      children: _renderContent(),
    );
  }

}